import React, { useState, useEffect } from "react";
import {
  StyleSheet,
  View,
  TouchableOpacity,
  ScrollView,
  Switch,
  Alert,
} from "react-native";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { useRouter } from "expo-router";

import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import { Colors } from "@/constants/Colors";
import { useTheme, FontSize } from "@/contexts/ThemeContext";
import { useAuth } from "@/contexts/AuthContext";

export default function SettingsScreen() {
  const { colorScheme, toggleColorScheme, fontSize, setFontSize } = useTheme();
  const tintColor = Colors[colorScheme ?? "light"].tint;
  const router = useRouter();
  const { logout } = useAuth();

  // 设置状态
  const [notificationsEnabled, setNotificationsEnabled] = useState(true);
  const [locationEnabled, setLocationEnabled] = useState(true);
  const [darkModeEnabled, setDarkModeEnabled] = useState(
    colorScheme === "dark"
  );
  const [fontSizeIndex, setFontSizeIndex] = useState(
    fontSize === "small" ? 0 : fontSize === "medium" ? 1 : 2
  ); // 0: 小, 1: 中, 2: 大

  // 监听深色模式变化
  useEffect(() => {
    setDarkModeEnabled(colorScheme === "dark");
  }, [colorScheme]);

  // 处理深色模式切换
  const handleDarkModeToggle = (value: boolean) => {
    setDarkModeEnabled(value);
    toggleColorScheme();
  };

  // 处理字体大小变化
  const handleFontSizeChange = (index: number) => {
    setFontSizeIndex(index);
    const newSize: FontSize =
      index === 0 ? "small" : index === 1 ? "medium" : "large";
    setFontSize(newSize);
  };

  // 处理退出登录
  const handleLogout = () => {
    Alert.alert("确认退出", "您确定要退出登录吗？", [
      { text: "取消", style: "cancel" },
      { text: "确定", onPress: () => logout() },
    ]);
  };

  // 字体大小选项
  const fontSizeOptions = ["小", "中", "大"];

  // 渲染设置项
  const renderSettingItem = (icon, title, description, rightComponent) => (
    <View style={styles.settingItem}>
      <View style={styles.settingItemLeft}>
        <MaterialCommunityIcons
          name={icon}
          size={24}
          color={tintColor}
          style={styles.settingIcon}
        />
        <View style={styles.settingTextContainer}>
          <ThemedText style={styles.settingTitle}>{title}</ThemedText>
          {description && (
            <ThemedText style={styles.settingDescription}>
              {description}
            </ThemedText>
          )}
        </View>
      </View>
      <View style={styles.settingItemRight}>{rightComponent}</View>
    </View>
  );

  // 渲染开关设置项
  const renderSwitchSetting = (
    icon,
    title,
    description,
    value,
    onValueChange
  ) => {
    return renderSettingItem(
      icon,
      title,
      description,
      <Switch
        value={value}
        onValueChange={onValueChange}
        trackColor={{ false: "#D1D1D1", true: tintColor }}
        thumbColor={"#FFFFFF"}
      />
    );
  };

  // 渲染导航设置项
  const renderNavigationSetting = (icon, title, description, onPress) => {
    return renderSettingItem(
      icon,
      title,
      description,
      <TouchableOpacity onPress={onPress}>
        <MaterialCommunityIcons name='chevron-right' size={24} color='#888' />
      </TouchableOpacity>
    );
  };

  // 动态样式
  const dynamicStyles = {
    fontSizeOptionActive: {
      backgroundColor: tintColor,
    },
  };

  return (
    <ThemedView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          onPress={() => router.back()}
          style={styles.backButton}
        >
          <MaterialCommunityIcons
            name='arrow-left'
            size={28}
            color={tintColor}
          />
        </TouchableOpacity>
        <ThemedText style={styles.headerTitle}>设置</ThemedText>
        <View style={styles.placeholder} />
      </View>

      <ScrollView style={styles.scrollView}>
        <View style={styles.settingSection}>
          <ThemedText style={styles.sectionTitle}>通知设置</ThemedText>
          {renderSwitchSetting(
            "bell",
            "推送通知",
            "接收新消息、活动提醒等通知",
            notificationsEnabled,
            setNotificationsEnabled
          )}
        </View>

        <View style={styles.settingSection}>
          <ThemedText style={styles.sectionTitle}>隐私设置</ThemedText>
          {renderSwitchSetting(
            "map-marker",
            "位置服务",
            "允许应用访问您的位置信息",
            locationEnabled,
            setLocationEnabled
          )}
        </View>

        <View style={styles.settingSection}>
          <ThemedText style={styles.sectionTitle}>显示设置</ThemedText>
          {renderSwitchSetting(
            "theme-light-dark",
            "深色模式",
            "切换应用的深色/浅色主题",
            darkModeEnabled,
            handleDarkModeToggle
          )}

          {renderSettingItem(
            "format-font-size-increase",
            "字体大小",
            "调整应用内文字的大小",
            <View style={styles.fontSizeSelector}>
              {fontSizeOptions.map((size, index) => (
                <TouchableOpacity
                  key={index}
                  style={[
                    styles.fontSizeOption,
                    fontSizeIndex === index &&
                      dynamicStyles.fontSizeOptionActive,
                  ]}
                  onPress={() => handleFontSizeChange(index)}
                >
                  <ThemedText
                    style={[
                      styles.fontSizeText,
                      fontSizeIndex === index && styles.fontSizeTextActive,
                    ]}
                  >
                    {size}
                  </ThemedText>
                </TouchableOpacity>
              ))}
            </View>
          )}
        </View>

        <View style={styles.settingSection}>
          <ThemedText style={styles.sectionTitle}>账户设置</ThemedText>
          {renderNavigationSetting(
            "account-edit",
            "编辑个人资料",
            "修改您的个人信息和兴趣爱好",
            () => router.push("/profile/edit-profile")
          )}

          {renderNavigationSetting(
            "lock-reset",
            "修改密码",
            "更新您的账户密码",
            () => router.push("/profile/change-password")
          )}
        </View>

        <View style={styles.settingSection}>
          <ThemedText style={styles.sectionTitle}>其他</ThemedText>
          {renderSettingItem(
            "information",
            "关于我们",
            "了解应用的更多信息",
            <MaterialCommunityIcons
              name='chevron-right'
              size={24}
              color='#888'
            />
          )}

          {renderNavigationSetting(
            "help-circle",
            "帮助与反馈",
            "获取帮助或提交反馈",
            () => router.push("/profile/help")
          )}
        </View>

        <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
          <ThemedText style={styles.logoutButtonText}>退出登录</ThemedText>
        </TouchableOpacity>
      </ScrollView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingTop: 60,
    paddingBottom: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: "#E1E1E1",
  },
  backButton: {
    width: 40,
    height: 40,
    justifyContent: "center",
    alignItems: "flex-start",
  },
  headerTitle: {
    fontSize: 22,
    fontWeight: "bold",
  },
  placeholder: {
    width: 40,
  },
  scrollView: {
    flex: 1,
  },
  settingSection: {
    paddingVertical: 15,
    borderBottomWidth: 1,
    borderBottomColor: "#E1E1E1",
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "bold",
    marginBottom: 15,
    paddingHorizontal: 20,
  },
  settingItem: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingVertical: 12,
    paddingHorizontal: 20,
  },
  settingItemLeft: {
    flexDirection: "row",
    alignItems: "center",
    flex: 1,
  },
  settingIcon: {
    marginRight: 15,
  },
  settingTextContainer: {
    flex: 1,
  },
  settingTitle: {
    fontSize: 16,
    marginBottom: 4,
  },
  settingDescription: {
    fontSize: 14,
    color: "#666",
  },
  settingItemRight: {
    marginLeft: 10,
  },
  fontSizeSelector: {
    flexDirection: "row",
    borderWidth: 1,
    borderColor: "#E1E1E1",
    borderRadius: 8,
    overflow: "hidden",
  },
  fontSizeOption: {
    paddingVertical: 6,
    paddingHorizontal: 12,
    backgroundColor: "#F5F5F5",
  },
  fontSizeText: {
    fontSize: 14,
    color: "#666",
  },
  fontSizeTextActive: {
    color: "#FFFFFF",
    fontWeight: "500",
  },
  logoutButton: {
    marginVertical: 30,
    marginHorizontal: 20,
    backgroundColor: "#FF6B6B",
    paddingVertical: 15,
    borderRadius: 10,
    alignItems: "center",
  },
  logoutButtonText: {
    color: "#FFFFFF",
    fontSize: 16,
    fontWeight: "bold",
  },
});
